package com.bilubi.reggie.reggie.filter;

import com.alibaba.fastjson2.JSON;
import com.bilubi.reggie.reggie.bean.Employee;
import com.bilubi.reggie.reggie.bean.User;
import com.bilubi.reggie.reggie.common.BaseContext;
import com.bilubi.reggie.reggie.common.R;
import com.bilubi.reggie.reggie.enums.CodeEnum;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;
import java.nio.file.PathMatcher;


@Slf4j
public class LoginFilter implements Filter {

    private final static String[] URLS = new String[]{"/backend/**", "/front/**", "/employee/login", "/employee/logout", "/user/sendMsg", "/user/login"};
    private final static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("拦截到请求:{}", request.getRequestURI());

        Employee employee = (Employee) request.getSession().getAttribute("employee");
        User user = (User) request.getSession().getAttribute("user");

        boolean check = checkUrls(request);
        if (employee != null || check || user != null) {
            if (employee != null) {
                BaseContext.setValue(employee.getId());
            }
            if (user != null) {
                BaseContext.setValue(user.getId());
            }
            log.info("请求{}放行", request.getRequestURI());
            filterChain.doFilter(request, servletResponse);
        }
        else {
            log.info("请求{}驳回", request.getRequestURI());
            response.getWriter().write(JSON.toJSONString(R.error(CodeEnum.NOT_LOGIN)));
        }
    }

    private boolean checkUrls(HttpServletRequest request) {
        for (String url : URLS) {
            if (antPathMatcher.match(url, request.getRequestURI())) {
                return true;
            }
        }
        return false;
    }
}
